//
//  VideoVC.m
//  DemoNIM
//
//  Created by chenzm on 2018/8/20.
//  Copyright © 2018年 chenzm. All rights reserved.
//

#import "VideoVC.h"
//thirds
#import <NIMSDK/NIMSDK.h>
#import <NIMAVChat/NIMAVChat.h>

#import "NTESGLView.h"



//设备宽高
#define kIphone_W [UIScreen mainScreen].bounds.size.width
#define kIphone_H [UIScreen mainScreen].bounds.size.height

@interface VideoVC ()<NIMNetCallManagerDelegate>

///视频配置
@property(nonatomic,copy)NIMNetCallVideoCaptureParam *param;
///视频会议
@property(nonatomic,copy)NIMNetCallMeeting *meeting;
///视频窗口
@property(nonatomic,strong)NTESGLView *remoteGLView;


///当前摄像头名字
@property (nonatomic, strong) NSString * currentCamare;
///
@property(nonatomic,copy)NSString *nimRoomName;

///按钮
@property(nonatomic,strong)UIButton *btn;

@end

@implementation VideoVC{
    
}


#pragma mark - initial
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setBaseData];
    [self setBaseUI];
}

-(void)setBaseData{
    self.nimRoomName = @"xxx";
    self.currentCamare = @"xxx";
    
    //加入视频房间
    [self joinNetCall:self with:self.nimRoomName];
}

-(void)setBaseUI{
    self.view.backgroundColor = [UIColor purpleColor];
    [self remoteGLView];
    [self btn];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - NIMNetCallManager 云信管理
///加入房间
- (void)joinNetCall:(UIViewController<NIMNetCallManagerDelegate> *)delegate with:(NSString *)roomName{
    self.meeting.name = roomName;
    [self joinNetCallWithRMeeting:self.meeting delegate:delegate];
}

//加入
- (void)joinNetCallWithRMeeting:(NIMNetCallMeeting *)rMeeting delegate:(UIViewController<NIMNetCallManagerDelegate> *)vc{
    NSLog(@"😎😎😎😎===准备加入会议");
    [[NIMAVChatSDK sharedSDK].netCallManager setMeetingRole:NO];//观众模式
    [[NIMAVChatSDK sharedSDK].netCallManager selectVideoAdaptiveStrategy:NIMAVChatVideoAdaptiveStrategySmooth];
    [[NIMAVChatSDK sharedSDK].netCallManager addDelegate:vc];
    
    [[NIMAVChatSDK sharedSDK].netCallManager joinMeeting:rMeeting completion:^(NIMNetCallMeeting * _Nonnull meeting, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"=========加入会议成功");
        }else{
            NSLog(@"%@",error.domain);
        }
    }];
}

//离开房间
- (void)leaveRoom:(NSString *)roomName delegate:(UIViewController<NIMNetCallManagerDelegate> *)delegate{
    self.meeting.name = roomName;
    [[NIMAVChatSDK sharedSDK].netCallManager leaveMeeting:self.meeting];
    [[NIMAVChatSDK sharedSDK].netCallManager removeDelegate:delegate];
    [_remoteGLView removeFromSuperview];
    _remoteGLView = nil;
    self.meeting = nil;
    self.param = nil;
}

#pragma mark - ------NIMNetCallManagerDelegate------
//远程视频 YUV 数据就绪
//480*640
- (void)onRemoteYUVReady:(NSData *)yuvData width:(NSUInteger)width height:(NSUInteger)height from:(NSString *)user {
    if ([user isEqualToString:self.currentCamare]) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [_remoteGLView render:yuvData width:width height:height];
            NSLog(@"\n👺👺👺👺👺\n%ld\n%@",yuvData.length,yuvData);
        });
    }
}
///用户加入了多人会议
- (void)onUserJoined:(NSString *)uid meeting:(NIMNetCallMeeting *)meeting{
    
}
//音量回调
-(void)onMyVolumeUpdate:(UInt16)volume{
    //刷新音量UI
    NSLog(@"%d",volume);
}


///服务器录制信息回调
- (void)onNetCallRecordingInfo:(NIMNetCallRecordingInfo *)info{
    
}
///当前通话网络状态
- (void)onNetStatus:(NIMNetCallNetStatus)status
               user:(NSString *)user{
    NSLog(@"网络状态：%ld and 用户 ：%@",(long)status,user);
    if ([user isEqualToString:self.currentCamare]) {
//        [self changeSignal:status];
    }
}


#pragma mark - method
- (UIViewContentMode)videochatRemoteVideoContentMode
{
    NSInteger setting = [[[NSUserDefaults standardUserDefaults] objectForKey:@"videochat_remote_video_content_mode"] integerValue];
    return (setting == 0) ? UIViewContentModeScaleAspectFill : UIViewContentModeScaleAspectFit;
}

-(void)btnAction:(UIButton *)sender{
    __weak typeof(self) weakSelf = self;
    [self dismissViewControllerAnimated:YES completion:^{
        [weakSelf leaveRoom:weakSelf.nimRoomName delegate:weakSelf];
    }];
}

#pragma mark - lazyload
-(UIButton *)btn{
    if (!_btn) {
        _btn = [UIButton buttonWithType:UIButtonTypeCustom];
        _btn.frame = CGRectMake(100, 20, 100, 50);
        _btn.backgroundColor = [UIColor redColor];
        [_btn setTitle:@"点击返回" forState:UIControlStateNormal];
        [_btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_btn];
    }
    return _btn;
}


///视频配置
- (void)fillVideoCaptureSetting:(NIMNetCallVideoCaptureParam *)param{
    param.preferredVideoQuality = NIMNetCallVideoQuality480pLevel;
    param.videoCrop  = NIMNetCallVideoCrop4x3;
    param.videoFrameRate = NIMNetCallVideoFrameRate20FPS;
    param.videoHandler = ^(CMSampleBufferRef  _Nonnull sampleBuffer) {
        NSLog(@"%@",sampleBuffer);
    };
}

- (NIMNetCallVideoCaptureParam *)param{
    if (!_param) {
        _param = [[NIMNetCallVideoCaptureParam alloc]init];
        [self fillVideoCaptureSetting:_param];
    }
    return _param;
}

- (NIMNetCallMeeting *)meeting{
    if (!_meeting) {
        _meeting = [[NIMNetCallMeeting alloc] init];
        _meeting.type = NIMNetCallMediaTypeVideo;
        _meeting.actor = NO;
        _meeting.option.voiceDetect = NO;
        _meeting.option.videoCaptureParam = self.param;
        _meeting.option.pureVideo = YES;
    }
    return _meeting;
}


-(NTESGLView *)remoteGLView{
    if (!_remoteGLView) {
        _remoteGLView = [[NTESGLView alloc] initWithFrame:CGRectMake(0, 100, kIphone_W, kIphone_W*0.75)];
        _remoteGLView.backgroundColor = [UIColor greenColor];
        [_remoteGLView setContentMode:[self videochatRemoteVideoContentMode]];
        [_remoteGLView setBackgroundColor:[UIColor clearColor]];
        [self.view addSubview:_remoteGLView];
    }
    return _remoteGLView;
}



@end
